package com.example.demo.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TimeZone;

public class JsonUtil {
    /**
     * json转对象
     *
     * @param json
     * @param klass
     * @param <T>
     * @return
     * @throws JsonProcessingException
     */
    public static <T> T json2Obj(String json, Class<T> klass) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //反序列化的时候如果多了其他属性,不抛出异常
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        return mapper.readValue(json, klass);
    }

    /**
     * json转复杂对象（含泛型对象）
     *
     * @param json
     * @param typeReference
     * @param <T>
     * @return
     * @throws JsonProcessingException
     */
    public static <T> T json2GenericsObj(String json, TypeReference<T> typeReference) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //反序列化的时候如果多了其他属性,不抛出异常
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        return mapper.readValue(json, typeReference);
    }

    /**
     * 对象转json
     *
     * @param obj
     * @return
     * @throws JsonProcessingException
     */
    public static String obj2Json(Object obj) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(obj);
    }

    /**
     *
     * @param request
     * @param klass
     * @param <T>
     * @return
     */
    public static <T> T getObjByRequest(HttpServletRequest request, Class<T> klass) throws IOException {
        try (BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"))) {
            StringBuilder rsb = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                rsb.append(inputStr);
            }
            return json2Obj(rsb.toString(), klass);
        }
    }

}

